// 云函数入口文件
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context })

	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken)
    if (!uid) {
      return { code: 403, msg: '身份验证失败' }
    }
	if(body.profileCompleted === undefined){
		return{
			code: 400,
			msg: '缺少profileCompleted参数', 
		}
	}
	 // 2. 参数校验
	    if (typeof body.profileCompleted !== 'boolean') {
	      return { 
	        code: 400, 
	        msg: '参数错误', 
	        detail: 'profileCompleted 必须为布尔值(true或false)' 
	      }
	    }


    const db = uniCloud.database()

    // 3. 更新 profileCompleted 字段
    await db.collection('uni-id-users').doc(uid).update({
      profileCompleted: body.profileCompleted
    })

	
    // 返回更新成功的消息
    return { code: 0, msg: 'profileCompleted 更新成功' }
  } catch (e) {
    return { code: 500, msg: '服务器错误', detail: e.message }
  }
}
